package com.leetcode.math;

import java.util.ArrayList;
import java.util.List;

public class SpiralOrder {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> resList = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return resList;
        }
        int row = 0;
        int col = 0;
        int total = matrix.length * matrix[0].length;
        boolean[][] isVisited = new boolean[matrix.length][matrix[0].length];
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1 ,0}};
        int directIndex = 0;
        for (int i = 0; i < total; i++) {
            resList.add(matrix[row][col]);
            isVisited[row][col] = true;
            int nextRow = row + directions[directIndex][0];
            int nextCol = col + directions[directIndex][1];
            if (nextRow < 0 || nextRow >= matrix.length || nextCol < 0
                    || nextCol >= matrix[0].length || isVisited[nextRow][nextCol]) {
                directIndex = (directIndex + 1) % 4;
            }
            row += directions[directIndex][0];
            col += directions[directIndex][1];
        }
        return resList;
    }
}
